package com.ysd.lis.service.lab.impl;

import cn.hutool.core.io.FileUtil;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import com.ysd.lis.entity.lab.*;
import com.ysd.lis.mapper.lab.*;
import com.ysd.lis.entity.lab.LabRptImageTemp;
import com.ysd.lis.mapper.lab.LabRptImageTempMapper;
import com.ysd.lis.request.AddLabMaininfo;
import com.ysd.lis.request.men.UploadImageDto;
import com.ysd.lis.service.lab.LabRptImageTempService;
import com.ysd.lis.request.lab.LabRptImageTempParam;
import com.ysd.lis.service.lab.LabRptresultImageService;
import com.ysd.lis.service.lab.LabRptresultService;
import com.ysd.util.PropertySlash;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import com.ysd.util.RedisUserManager;
import com.ysd.util.ToolsUtils;
import org.springframework.transaction.annotation.Transactional;
import com.ysd.common.Result;
import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.ysd.lis.entity.SysUser;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import java.io.File;
import java.sql.Timestamp;
import java.util.*;

/**
 * 检验结果图片表(LabRptImageTemp)表服务实现类
 *
 * @author leiming
 * @since 2024-11-15 14:11:48
 */
@Service("labRptImageTempService")
public class LabRptImageTempServiceImpl extends ServiceImpl<LabRptImageTempMapper, LabRptImageTemp> implements LabRptImageTempService {

    @Autowired
    LabMaininfoMapper labMaininfoMapper;
    @Autowired
    LabRptresultImageService labRptresultImageService;

    @Autowired
    LabRptresultService labRptresultService;

    @Autowired
    LabRptGroupMapper labRptGroupMapper;

    @Value("${picturePath}")
    private String picturePath;

    @Override
    public Result findImagesByMaininfoId(RptResultDto rptResultDto) {
        if (org.apache.commons.lang3.StringUtils.isBlank(rptResultDto.getRptGroup()) || org.apache.commons.lang3.StringUtils.isBlank(rptResultDto.getSampleNo()) || org.apache.commons.lang3.StringUtils.isBlank(rptResultDto.getSampleda())) {
            return Result.fail("参数不能为空");
        }
        Timestamp startTime = Timestamp.valueOf(rptResultDto.getSampleda().substring(0, 10) + " 00:00:00");
        Timestamp endTime = Timestamp.valueOf(rptResultDto.getSampleda().substring(0, 10) + " 23:59:59");

        LambdaQueryWrapper<LabRptImageTemp> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(LabRptImageTemp::getDelFlag, 0);

        // 添加一组条件，当RptGroup, SampleNo, Sampleda 都满足时
        queryWrapper.and(wrapper -> wrapper
                .eq(LabRptImageTemp::getRptGroup, rptResultDto.getRptGroup())
                .eq(LabRptImageTemp::getSampleNo, rptResultDto.getSampleNo())
                .ge(LabRptImageTemp::getSampleda, startTime)
                .le(LabRptImageTemp::getSampleda, endTime));

        // 或者添加另一个条件，仅根据MaininfoId查询
        //queryWrapper.or().eq(LabRptImageTemp::getMaininfoId, rptResultDto.getMaininfoId());
        queryWrapper.orderByAsc(LabRptImageTemp::getSeq);
        List<LabRptImageTemp> labRptImageTemps = this.baseMapper.selectList(queryWrapper);

        return Result.succ(1, "查询结果成功", labRptImageTemps);
    }

    @Override
    public Result saveOrUpdateImages(LabRptImageTemp labRptImageTemp) {

        boolean b = this.saveOrUpdate(labRptImageTemp);
        if (b) {
            return Result.succ(1, "成功", null);
        } else {
            return Result.fail(400, "失败", "");
        }
    }

    @Override
    public Result batchDeleteImages(List<String> imagesIds) {

        if (CollectionUtils.isEmpty(imagesIds)) {
            return Result.fail("请选择一条检验结果！");
        } else {
            boolean b = this.removeByIds(imagesIds);
            if (b) {
                return Result.succ(1, "删除成功！", null);
            } else {
                return Result.fail("删除失败！");
            }
        }
    }

    @Override
    public Result uploadImageFiles(UploadImageDto uploadImageDto) throws JsonProcessingException {
        //将base64字符串转为字节
        if (org.apache.commons.lang3.StringUtils.isBlank(uploadImageDto.getOrgId())) {
            LambdaQueryWrapper<LabRptGroup> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(LabRptGroup::getRptGroup, uploadImageDto.getRptGroup());
            lambdaQueryWrapper.eq(LabRptGroup::getDelFlag, 0);
            LabRptGroup labRptGroup = labRptGroupMapper.selectList(lambdaQueryWrapper).get(0);
            uploadImageDto.setOrgId(StringUtils.isBlank(labRptGroup.getOrgId()) ? "" : labRptGroup.getOrgId());
        }
        //需要在先创建labmaininfo
        //begin
        AddLabMaininfo addMainInfo=new AddLabMaininfo();
        addMainInfo.setRptGroup(uploadImageDto.getRptGroup());
        addMainInfo.setSampleda(Timestamp.valueOf(uploadImageDto.getSampleda() + " 00:00:00"));
        addMainInfo.setSampleNo(uploadImageDto.getSampleNo());
        addMainInfo.setReqNo("");
        Result addMainInfoRes = this.labRptresultService.addMaininfoByReqNo(addMainInfo);
        //end

        String base64Str = uploadImageDto.getFileData().replaceAll("data:image/jpeg;base64,", "");
        byte[] buffer = Base64.getDecoder().decode(base64Str);
        String folder = picturePath + "\\" + uploadImageDto.getSampleda().substring(0, 10) + "\\" + uploadImageDto.getInstrCode() + PropertySlash.getSlash();
        if (!FileUtil.exist(folder)) {
            FileUtil.mkdir(folder);
        }
        String fileName = uploadImageDto.getSampleda() + uploadImageDto.getRptGroup() + uploadImageDto.getSampleNo() + uploadImageDto.getInstrCode() + uploadImageDto.getFileName();
        String path = folder + fileName;
        File file1 = FileUtil.writeBytes(buffer, path);
        if (file1.length() < 0) {
            return Result.fail("文件上传失败");
        }
        LabRptImageTemp labRptImageTemp = new LabRptImageTemp();
        labRptImageTemp.setImageName(uploadImageDto.getFileName());
        labRptImageTemp.setRptGroup(uploadImageDto.getRptGroup());
        labRptImageTemp.setSampleNo(uploadImageDto.getSampleNo());
        labRptImageTemp.setSampleda(Timestamp.valueOf(uploadImageDto.getSampleda().substring(0, 10) + " 00:00:00"));
        labRptImageTemp.setImageUrl("/image/" + uploadImageDto.getSampleda().substring(0, 10) + "/" + uploadImageDto.getInstrCode() + "/" + fileName);
        labRptImageTemp.setImageExt(uploadImageDto.getFileType());
        //LabRptImageTemp.setMaininfoId(labMaininfo.getId());
        labRptImageTemp.setSeq(uploadImageDto.getSeq());
        labRptImageTemp.setOrgId(uploadImageDto.getOrgId());
        labRptImageTemp.setCreateTime(new Timestamp(System.currentTimeMillis()));
        int insert = this.baseMapper.insert(labRptImageTemp);
        if (insert > 0) {
            return Result.succ(1, "上传成功", "");
        } else {
            return Result.fail(400, "上传失败", "");
        }

    }

    @Override
    public Result selectImagesChecked(String id) {
        LabRptImageTemp info=this.baseMapper.selectById(id);
        LabRptresultImage labRptresultImage=new LabRptresultImage();
        BeanUtil.copyProperties(info,labRptresultImage);
        labRptresultImage.setId(null);
        labRptresultImageService.save(labRptresultImage);
        info.setResultId(labRptresultImage.getId());
        info.setIsChecked("1");
        this.baseMapper.updateById(info);
        return Result.succ("更新成功！");
    }

    @Override
    public Result unSelectImagesChecked(String id) {
        LabRptImageTemp info=this.baseMapper.selectById(id);
        LabRptresultImage labRptresultImage=new LabRptresultImage();
        BeanUtil.copyProperties(info,labRptresultImage);
        labRptresultImage.setId(null);
        labRptresultImageService.removeById(info.getResultId());
        info.setIsChecked("0");
        this.baseMapper.updateById(info);
        return Result.succ("更新成功！");
    }
}

